<template>
  <div class="user-password-view">
    <h1>修改密码</h1>
    <a-form
      :style="{ maxWidth: 480, margin: '0 auto', marginTop: '20px' }"
      label-align="left"
      :model="formState"
      name="basic"
      :label-col="{ span: 4 }"
      :wrapper-col="{ span: 22 }"
      autocomplete="off"
      @finish="handleSubmit"
      ref="formRef"
    >
      <a-form-item
        label="原密码"
        name="originPassword"
        :rules="[{ required: true, message: '请输入原密码' }]"
      >
        <a-input-password
          v-model:value="formState.originPassword"
          placeholder="请输入原密码"
        />
      </a-form-item>

      <a-form-item
        label="新密码"
        name="currentPassword"
        :rules="[
          { required: true, message: '请输入新密码' },
          { min: 8, message: '密码长度不能小于8位' },
        ]"
      >
        <a-input-password
          v-model:value="formState.currentPassword"
          placeholder="请输入新密码"
        />
      </a-form-item>
      <a-form-item
        label="确认密码"
        name="checkPassword"
        :rules="[
          { required: true, message: '请输入确认密码' },
          { min: 8, message: '密码长度不能小于8位' },
        ]"
      >
        <a-input-password
          v-model:value="formState.checkPassword"
          placeholder="请输入确认密码"
        />
      </a-form-item>
      <a-form-item
        :wrapper-col="{ offset: 4, span: 16 }"
        style="text-align: center"
      >
        <a-button type="primary" html-type="submit" class="remit-button">
          修改密码
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, watch } from "vue";
import { message } from "ant-design-vue";
import { userPassword } from "@/api/userSetting";

const originPassword = ref("");
const currentPassword = ref("");
const rePassword = ref("");

interface FormState {
  originPassword: string;
  currentPassword: string;
  checkPassword: string;
}

const formState = reactive<FormState>({
  originPassword: "",
  currentPassword: "",
  checkPassword: "",
});

const formRef = ref();

const handleSubmit = async (value: FormState) => {
  console.log("✅ changePassword 被触发");
  console.log("原密码:", originPassword.value);
  console.log("新密码:", currentPassword.value);
  console.log("确认密码:", rePassword.value);
  if (value.currentPassword !== value.checkPassword) {
    message.error("两次密码不一致");
    return;
  }
  const res = await userPassword({
    oldPassword: value.originPassword,
    newPassword: value.currentPassword,
  });
  if (res.data.code === 200) {
    message.success("修改成功");
    formRef.value.resetFields();
  } else {
    message.error(res.data.message);
  }
};
</script>

<style scoped></style>
